/**
 * 
 */
package t4j.concurrency;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

public class Pool<T> {
	private int size;
	private List<T> items = new ArrayList<T>();
	private volatile boolean[] checkedOut;
	private Semaphore available;

	public Pool(Class<T> classObject, int size) {
		this.size = size;
		checkedOut = new boolean[size];
		available = new Semaphore(size, true);

		for (int i = 0; i < size; i++) {
			try {
				items.add(classObject.newInstance());
			} catch (InstantiationException e) {

				e.printStackTrace();
			} catch (IllegalAccessException e) {
				
				e.printStackTrace();
			}
		}
	}

	/**
	 * 获取一个对象
	 */
	public T checkOut() throws InterruptedException {
		available.acquire();//获取一个许可，如果没有就等待
		return getItem();
	}

	/**
	 * 释放一个
	 * @param x
	 */
	public void checkIn(T x) {
		
		if (repleaseItem(x))
			available.release();//释放一个许可
	}

	//获取对象后，把checkedOut[i]设为true
	public synchronized T getItem() {
		for (int i = 0; i < size; i++)
			if (!checkedOut[i]) {
				checkedOut[i] = true;
				return items.get(i);
			}

		return null;
	}

	//释放一个对象，把checkedOut[i]设为false
	private synchronized boolean repleaseItem(T item) {
		int index = items.indexOf(item);

		if (index == -1)
			return false;//Not in the list

		if (checkedOut[index]) {
			checkedOut[index] = false;
			return true;
		}

		return false;
	}
}
